package com.xjtu.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author rt
 * @Date 2021/7/29 15:35
 * @Version 1.0
 */
@Component
public class WebSocketServer {
    private static class SingletonWSServer {
        static final WebSocketServer instance = new WebSocketServer();
    }

    public static WebSocketServer getInstance() {
        return SingletonWSServer.instance;
    }

    //负责处理新客户端的接入
    private EventLoopGroup boss;
    //负责处理客户端的网络请求
    private EventLoopGroup worker;
    private ServerBootstrap server;
    private ChannelFuture future;

    public WebSocketServer() {
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(boss, worker)
                //默认通道类型
                .channel(NioServerSocketChannel.class)
                //处理websocket消息
                .childHandler(new WSServerInitializer());
    }

    @PostConstruct
    public void start() {
        int port = 8888;
        try {
            this.future = server.bind(port).sync();
            System.out.println("端口绑定成功：" + port);
        } catch (InterruptedException e) {
            System.out.println("端口已被占用：" + port);
        }
    }
}
